package datastructure.trie;

import java.util.TreeMap;

/**
 * @author XY
 * @version 1.0
 * @date 2021/12/23 10:45
 * @Description trie
 */
public class Trie {

    private class Node{
        //标识该节点是否是一个字符串的结尾
        public boolean isWord;
        //用map直接标识下一个节点的值，和指向的下一个节点
        public TreeMap<Character,Node> next;

        public Node(){
            this(false);
        }

        public Node(boolean isWord){
            this.isWord=isWord;
            next = new TreeMap<>();
        }
    }

    private Node root;
    //trie中存储的完整的单词数量，不是节点数量
    private int size;

    public Trie(){
        root = new Node();
        size = 0;
    }

    public int getSize(){
        return size;
    }

    public void add(String word){

        Node cur = root;

        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            //如果不进入if则说明当前字符已经存在
            if(cur.next.get(c)==null){
                cur.next.put(c,new Node());
            }
            cur = cur.next.get(c);
        }
        //先判断当前单词之前不是一个完整的单词的时候才进行操作
        if(!cur.isWord){
            cur.isWord = true;
            size++;
        }
    }

    public void addF(String word){
        add2(word,root,0);
    }

    public void add2(String word,Node node,int index){
        if(index>=word.length()){
            if(!node.isWord){
                node.isWord=true;
                size++;
            }
            return ;
        }
        char c1 = word.charAt(index);
        if(node.next.get(c1)==null){
            node.next.put(c1,new Node());
        }
        index++;
        add2(word,node.next.get(c1),index);
    }

    //查询单词是否在trie树中
    public boolean contains(String word){
        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if(cur.next.get(c)==null){
                return false;
            }
            cur = cur.next.get(c);
        }
        //panda  中查找 pan  如果n的isword为false的话就失败了
        return cur.isWord;
    }

    //前缀搜索,查询在trie中是否有单词以prefix为前缀
    public boolean isPrefix(String prefix){
        Node cur = root;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if(cur.next.get(c)==null){
                return false;
            }
            cur = cur.next.get(c);
        }
        return true;
    }

}
